/**
 * 修正后的API测试脚本
 * 基于用户提供的curl命令创建
 */

import fs from 'fs';
import path from 'path';
import http from 'http';
import https from 'https';
import { fileURLToPath } from 'url';

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 加载配置
const loadConfig = () => {
    try {
        const configPath = path.join(__dirname, 'env.config');
        const content = fs.readFileSync(configPath, 'utf8');
        const config = {};

        content.split('\n').forEach(line => {
            if (line.trim().startsWith('#') || !line.trim()) return;

            const match = line.match(/^([A-Z0-9_]+)="([^"]*)"/);
            if (match) {
                const [, key, value] = match;
                config[key] = value;
            }
        });

        return config;
    } catch (error) {
        console.error('加载配置文件失败:', error);
        process.exit(1);
    }
};

// 发送HTTP请求
const sendRequest = (url, method = 'GET', headers = {}, body = null) => {
    return new Promise((resolve, reject) => {
        try {
            const parsedUrl = new URL(url);
            const options = {
                hostname: parsedUrl.hostname,
                port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
                path: parsedUrl.pathname + parsedUrl.search,
                method: method,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json, text/plain, */*',
                    'Pragma': 'no-cache',
                    'Cache-Control': 'no-cache',
                    'isToken': 'false',
                    ...headers
                },
                timeout: 5000 // 5秒超时
            };

            console.log(`发送${method}请求到: ${url}`);
            console.log(`请求头:`, JSON.stringify(options.headers, null, 2));
            if (body) {
                console.log(`请求体:`, JSON.stringify(body, null, 2));
            }

            const client = parsedUrl.protocol === 'https:' ? https : http;
            const req = client.request(options, (res) => {
                let data = '';

                res.on('data', (chunk) => {
                    data += chunk;
                });

                res.on('end', () => {
                    console.log(`状态码: ${res.statusCode}`);

                    // 尝试解析JSON
                    let parsedData = null;
                    let parseError = null;

                    if (data) {
                        try {
                            parsedData = JSON.parse(data);
                            console.log('完整响应:', JSON.stringify(parsedData, null, 2));
                        } catch (error) {
                            parseError = error;
                            console.log('原始响应:', data);
                        }
                    }

                    resolve({
                        statusCode: res.statusCode,
                        headers: res.headers,
                        data: parsedData,
                        rawData: data,
                        parseError: parseError
                    });
                });
            });

            req.on('error', (error) => {
                console.error(`请求失败: ${error.message}`);
                reject(error);
            });

            req.on('timeout', () => {
                console.error('请求超时');
                req.destroy();
                reject(new Error('请求超时'));
            });

            if (body) {
                req.write(typeof body === 'string' ? body : JSON.stringify(body));
            }

            req.end();
        } catch (error) {
            console.error(`创建请求失败: ${error.message}`);
            reject(error);
        }
    });
};

// 测试不同的API路径组合
const testApiUrls = async () => {
    const config = loadConfig();
    const PROJECT_ID = config.PROJECT_ID;

    console.log('项目ID:', PROJECT_ID);

    // 从curl命令获取的参数格式
    const requestBody = { id: PROJECT_ID };

    // 测试不同的URL组合
    const urlFormats = [
        // 本地地址
        { label: '本地地址-curl格式', url: 'http://localhost:8001/auto-api/autoapi/get_token' },

        // 远程地址变种
        { label: '原始URL', url: config.AUTO_API_BASE_URL + '/get_token' },
        { label: '修改路径-auto-api', url: `http://144.123.108.22:3406/auto-api/autoapi/get_token` },
        { label: '修改路径-api', url: `http://144.123.108.22:3406/api/autoapi/get_token` },
        { label: '修改路径-autoapi', url: `http://144.123.108.22:3406/autoapi/get_token` },
        { label: '修改路径直接/get_token', url: `http://144.123.108.22:3406/get_token` },

        // 尝试不同的路径组合
        { label: '本地端口-原路径', url: `http://localhost:3406/tls/dev-api/autoapi/get_token` },
        { label: '本地端口8001-原路径', url: `http://localhost:8001/tls/dev-api/autoapi/get_token` }
    ];

    for (const format of urlFormats) {
        console.log(`\n===== 测试 ${format.label} =====`);
        console.log(`URL: ${format.url}`);

        try {
            const response = await sendRequest(format.url, 'POST', {}, requestBody);

            if (response.statusCode >= 200 && response.statusCode < 300 && response.data) {
                console.log('请求成功!');

                // 如果成功获取令牌，保存到文件
                if (response.data.data && response.data.data.token) {
                    const token = response.data.data.token;
                    const tokenPath = path.join(__dirname, 'token.json');
                    fs.writeFileSync(tokenPath, JSON.stringify({ token }, null, 2));
                    console.log(`令牌已保存到: ${tokenPath}`);

                    // 更新环境配置文件
                    const configJsPath = path.join(__dirname, 'env.config.js');
                    fs.writeFileSync(configJsPath, `
/**
 * 金牛座API文档与类型生成工具 - API配置
 * 成功的API URL配置
 */
export default {
    AUTO_API_BASE_URL: "${format.url.replace('/get_token', '')}",
    PROJECT_ID: "${PROJECT_ID}",
    SCHEMA_NAME: "${config.SCHEMA_NAME}"
};
`);
                    console.log(`成功的API URL已保存到: ${configJsPath}`);

                    // 停止测试，因为我们找到了正确的URL
                    return true;
                }
            } else {
                console.log('请求失败');
            }
        } catch (error) {
            console.error('请求错误:', error);
        }
    }

    return false;
};

// 主函数
const main = async () => {
    console.log('=== 修正后的API测试开始 ===');

    const success = await testApiUrls();

    if (!success) {
        console.log('\n所有URL组合都测试失败');
    }

    console.log('\n=== 测试完成 ===');
};

// 执行主函数
main().catch(error => {
    console.error('测试过程中发生错误:', error);
    process.exit(1);
}); 